<!-- 采购合同编辑 -->
<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field readonly v-model="formData.billNumber" name="入库单编号" label="入库单编号" input-align="right" placeholder="请输入" />
        <van-field v-model="formData.supplierName" name="供应商" label="供应商" input-align="right" placeholder="请选择" right-icon="arrow" readonly />
        <van-field v-model="formData.preDate" name="预计到达日期" label="预计到达日期" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelectTime('preDate')" :rules="[{ required: true }]" readonly />
        <van-field v-model="formData.fixCenterName" readonly name="售后服务部" label="售后服务部" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('fixCenterId', 'fixCenterName')" :rules="[{ required: true }]" />
        <div class="car_title">入库信息</div>

        <van-field v-model="formData.departMentOrgName" readonly name="所属品牌" label="所属品牌" input-align="right" placeholder="请选择" right-icon="arrow" />
        <!-- @click="handleSelect('departMentOrgNameId', 'departMentOrgName')" -->
        <van-field v-model="formData.wareHouseName" readonly name="入库仓库" label="入库仓库" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('wareHouseId', 'wareHouseName')" :rules="[{ required: true }]" />
        <van-field v-model="formData.showOrgName" readonly name="展厅" label="展厅" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('showOrgId', 'showOrgName')" :rules="[{ required: true }]" />

        <van-field required v-model="formData.remark" name="备注" label="备注" type="textarea" input-align="left" placeholder="请输入备注" :rules="[{ required: true }]" />
        <div class="car_title">车辆信息</div>
        <van-field readonly v-model="billNumber" name="采购合同号" label="采购合同号" input-align="right" placeholder="请输入" />
        <van-field v-model="formData.vinCode" readonly name="车架号" label="车架号" input-align="right" placeholder="请选择" />

        <van-field v-model="formData.carMiles" name="车辆公里数" label="车辆公里数" input-align="right" placeholder="请输入" :rules="[{ required: true }]" required>
          <template slot="button">km</template>
        </van-field>
        <van-field v-model="formData.keyQty" name="钥匙数量" label="钥匙数量" input-align="right" placeholder="请输入" :rules="[{ required: true }]" required />
        <div class="car_title">运输投保信息</div>
        <van-field required name="radio" label="是否品牌采购" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.brandPurchase" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field required name="radio" label="投保类型" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.insureType" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in stockTransInsureTypeList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field v-if="formData.insureType == 2" required v-model="formData.noInsureReason" name="不投保原因" label="不投保原因" type="textarea" input-align="left" placeholder />

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field name="模糊查询" v-if="likeWhoField == 'wareHouseId'" input-align="left" v-model="likeWho" label="模糊查询" placeholder="请输入模糊查询关键词" />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>

        <!-- 时间选择弹窗 -->
        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @confirm="onTimeConfirm($event)" @cancel="showTimerPicker = false" :formatter="formatter" />
        </van-popup>
        <div class="footerBtn">
          <div class="saveBtn" @click="formOnSubmit(1)">保存</div>
          <div class="submitBtn" @click="formOnSubmit(2)">提交</div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Tab,
  Tabs,
  ImagePreview,
  Notify
} from "vant";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";
import commonApi from "@/api/commonApi";
export default {
  name: "PaymentOrderEdit",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Tab,
    Tabs,
    ImagePreview,
    Notify
  },
  data() {
    return {
      likeWho: "", // 模糊查询关键词
      likeWhoField: "", // 模糊查询的对象
      showTimerPicker: false,
      formData: {
        saveOrSubmit: "", //固定值,save是保存动作,submit是提交
        signCompanyId: "",
        preDate: "", //预计到达日期，String，提交必填
        showOrgId: "", //展厅ID,提交必填，String
        wareHouseId: "", //入库仓库ID,提交必填，String
        remark: "", //备注,提交必填，String
        carMiles: "", //车辆公里数,非必填，String
        keyQty: "", //钥匙数量,非必填，String
        brandPurchase: 0, //是否品牌采购,提交必填，String
        insureType: "", //投保类型,提交必填，String
        insureTypeValue: "",
        noInsureReason: "", //不投保原因,提交必填，String
        orgId: "", //登录组织ID,必填，String
        userId: "" //用户ID，必填，String
      },
      orderId: "",
      billNumber: "",

      columns: [],
      showSelectPicker: false,
      detailId: "",
      userId: getCookies("userId"), //用户ID，必填，String
      isflagList: [
        { name: "是", value: 1 },
        { name: "否", value: 0 }
      ],
      currentDate: new Date(),
      showOrgList: [],
      issureTypeList: [],
      fixcenterList: [],
      wareHouseList: [],
      stockTransInsureTypeList: []
    };
  },
  watch: {
    likeWho: function(nval, oval) {
      if (nval) {
        let newArr = this.wareHouseList.filter(item => {
          return item.name.indexOf(nval) > -1;
        });
        console.log(newArr);
        this.columns = newArr;
      } else {
        this.columns = this.wareHouseList;
      }
    }
  },
  mounted() {
    if (this.$route.query) {
      this.detailId = this.$route.query.billId;
      this.getDetail(this.detailId);
      this.orderId = this.$route.query.orderId;
      this.billNumber = this.$route.query.billNumber;
    }
  },
  methods: {
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          billId,
          method: "getPurchaeInWareHouseById"
        })
        .then(res => {
          if (res.code == 1) {
            for (const key in res.data) {
              if (res.data[key] == null || res.data[key] == undefined) {
                res.data[key] = "";
              }
            }
            // this.formData.issureType = res.data.insureTypeValue
            res.data.insureType = res.data.insureTypeValue;
            res.data.brandPurchase = Number(res.data.brandPurchaseValue);
            // res.data.vinCode = res.data.vinCode
            // res.data.keyQty = res.data.keyQty
            // res.data.carMiles = res.data.carMiles
            console.log(this.formData);

            this.formData = { ...this.formData, ...res.data };

            this.getStockTransFixcenter();
            this.getWareHouse();
            this.getStockTransInsureType();
            if (
              this.formData.departMentOrgNameId &&
              this.formData.wareHouseId
            ) {
              this.getPurInShowOrg();
            }
          }
        });
    },
    // 售后服务部
    getStockTransFixcenter() {
      sellManageApi
        .secondHandCarFacade({
          departMentOrgId: this.formData.departMentOrgNameId, //品牌
          method: "getStockTransFixcenter"
        })
        .then(res => {
          if (res.code == 1) {
            this.fixcenterList = res.data;
          }
        });
    },
    // 展厅
    getPurInShowOrg() {
      sellManageApi
        .secondHandCarFacade({
          departMentOrgId: this.formData.departMentOrgNameId, //品牌
          inWarehouseId: this.formData.wareHouseId, //仓库
          method: "getPurInShowOrg"
        })
        .then(res => {
          if (res.code == 1) {
            this.showOrgList = res.data;
          }
        });
    },
    // 仓库
    getWareHouse() {
      sellManageApi
        .secondHandCarFacade({
          method: "getWareHouse"
        })
        .then(res => {
          if (res.code == 1) {
            this.wareHouseList = res.data;
          }
        });
    },

    // 投保类型
    getStockTransInsureType() {
      commonApi
        .getEnums({
          key: "stockTransInsureType",
          userId: this.userId
        })
        .then(res => {
          if (res.data) {
            let data = [];
            res.data.forEach((item, index) => {
              if (item.name) {
                data.push(item);
              }
            });
            this.stockTransInsureTypeList = data;
          }
        });
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      if (field == "wareHouseId") {
        this.columns = this.wareHouseList;
      } else if (field == "departMentOrgNameId") {
        this.columns = this.showOrgList;
        // 缺少品牌接口
      } else if (field == "fixCenterId") {
        this.columns = this.fixcenterList;
      } else if (field == "showOrgId") {
        if (!this.formData.wareHouseId) {
          Notify({ type: "danger", message: "请先选择入库仓库" });
          return;
        }
        this.columns = this.showOrgList;
      }
      this.field = field;
      this.likeWhoField = field;
      this.fieldName = fieldName;
      this.showSelectPicker = true;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      if (
        this.field == "showOrgId" ||
        this.field == "wareHouseId" ||
        this.field == "fixCenterId"
      ) {
        this.formData[this.field] = value.billId;
        this.formData[this.fieldName] = value.name;
      } else {
        this.formData[this.field] = value.value;
        this.formData[this.fieldName] = value.name;
      }
      if (this.field == "wareHouseId") {
        this.formData.showOrgId = "";
        this.formData.showOrgName = "";
        this.getPurInShowOrg();
      }

      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day}`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field;
      this.showTimerPicker = true;
    },
    onTimeConfirm(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[this.timeField] = `${year}-${month}-${day} `;
      this.showTimerPicker = false;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    formOnSubmit(type) {
      this.$refs.form
        .validate()
        .then(() => {
          this.formData.insureTypeValue = this.formData.insureType;
          // this.formData.showOrgId = this.formData.departMentOrgNameId
          sellManageApi
            .secondHandCarFacade({
              ...this.formData,
              noInsureReason: this.formData.noInsureReason
                ? this.formData.noInsureReason
                : "",
              method: "updatePurchaeInWareHouse",
              saveOrSubmit: type == 1 ? "save" : "submit"
            })
            .then(res => {
              console.log(res);
              if (res.code == 1) {
                if (type == 1) {
                  Notify({ type: "success", message: "保存成功" });
                  // this.formData.billId = res.billId;
                } else {
                  Notify({ type: "success", message: "提交成功" });
                  this.$router.go(-1);
                }
              }
            });
          this.loading = true;
        })
        .catch(() => {
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 10px 10px;
    border-radius: 5px;
    background: #fff;
    padding: 15px;
    .detail_header_lt {
      .carNo {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 5px 5px;
          font-size: 12px;
          text-align: center;
          margin-left: 5px;
        }
      }
      .hank {
        font-size: 14px;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 5px;
          margin-right: 5px;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 14px;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 16px;
        padding: 5px;
        border-radius: 50%;
        margin-right: 5px;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.footerBtn {
  display: flex;
  justify-content: space-between;
  width: 80%;
  margin: auto;
  padding-bottom: 50px;
  background: #fff;
  margin-top: 25px;
  .saveBtn {
    background: #ccc;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
    margin-right: 10px;
  }
  .submitBtn {
    background: #409eff;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
  }
}
.car_title {
  padding: 10px;
  font-size: 15px;
  font-weight: bold;
  color: #333;
}
</style>
